#include <analyze_args.h>
#include <common.h>
#include <getopt.h>

std::string source_file_name;
std::string dot_file_name;
std::string ir_file_name;

std::string out_file_name;

char stage = ASM;

static struct option long_options[] = {
  {"help", optional_argument, NULL, HELP},
  {"dot_file", optional_argument, NULL, DOT_FILE},
  {"ir_file", optional_argument, NULL, IR_FILE},

  {"out_file", optional_argument, NULL, OUT_FILE},
  {NULL, 0, NULL, 0},
};

static void help() {
  std::cout <<
    R"(  _______              _     _ _                 )" << std::endl <<
    R"( |__   __|            | |   (_) |                )" << std::endl <<
    R"(    | | ___  _ __  ___| |__  _| |__  _   _ _ __  )" << std::endl <<
    R"(    | |/ _ \| '_ \/ __| '_ \| | '_ \| | | | '_ \ )" << std::endl <<
    R"(    | | (_) | |_) \__ \ | | | | | | | |_| | | | |)" << std::endl <<
    R"(    |_|\___/| .__/|___/_| |_|_|_| |_|\__,_|_| |_|)" << std::endl <<
    R"(            | |                                  )" << std::endl <<
    R"(            |_|                                  )" << std::endl <<
  std::endl;

  std::cout << "compiler help:😊" << std::endl;
  std::cout << std::endl;
  std::cout << "usage: compiler [options] <source_file>" << std::endl;
  std::cout << std::endl;
  std::cout << "options:" << std::endl;
  std::cout << "\t\t" << "-d" << "\t" << "just print dot file(must setting dot_file)" << std::endl;
  std::cout << "\t\t" << "-i" << "\t" << "just print ir file(must setting ir_file)" << std::endl;
  std::cout << "\t\t" << "-S" << "\t" << "just print asm file" << std::endl;
  std::cout << "\t" << "--dot_file" << "\t" << "dot source file" << std::endl;
  std::cout << "\t" << "--ir_file" << "\t" << "IR file" << std::endl;
  std::cout << "\t" << "-o --out_file" << "\t" << "output file" << std::endl;
  std::cout << "\t" << "--help" << "\t\t" << "print helpful information" << std::endl;
}

void analyze_args(int argc, char * argv[]) {
  int opt = 0;
  int option_index;
  while((opt = getopt_long(argc, argv, "o:diS", long_options, &option_index)) != -1) {
    switch(opt) {
    case DOT:
      stage = DOT;
      break;
    case IR:
      stage = IR;
      break;
    case ASM:
      stage = ASM;
      break;
    case HELP:
      help();
      exit(0);
    case DOT_FILE:
      dot_file_name = optarg;
      break;
    case IR_FILE:
      ir_file_name = optarg;
      break;
    case OUT_FILE:
      out_file_name = optarg;
      break;
    case '?':
      PrintErr("Invalid argument\n");
      help();
      exit(-1);
    default:
      std::cout << "code " << opt << std::endl;
      exit(-1);
    }
  }
  Assert(optind+1 <= argc, "missing arg: the number of args is %d", argc);
  source_file_name = argv[optind];
}
